// @ts-nocheck
import React, { useState, useEffect } from 'react';
// @ts-ignore 暂时忽略React Native类型错误
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  ActivityIndicator,
  Alert,
  TextInput,
  ScrollView,
  SafeAreaView,
  StatusBar,
  Platform,
} from 'react-native';
import DlnaPlayer from 'react-native-dlna-player';
// 使用类型导入解决组件不存在的问题
import type {
  StyleSheet as StyleSheetType,
  Text as TextType,
  View as ViewType,
  TouchableOpacity as TouchableOpacityType,
  ActivityIndicator as ActivityIndicatorType,
  Alert as AlertType,
  TextInput as TextInputType,
  ScrollView as ScrollViewType,
  SafeAreaView as SafeAreaViewType,
  StatusBar as StatusBarType,
} from 'react-native';

// 定义必要的类型（避免从库中导入）
interface Device {
  id?: string;
  deviceId?: string;
  name?: string;
  model?: string;
  modelName?: string;
}

interface PlaybackStatus {
  isPlaying: boolean;
  position: number;
  duration: number;
}

const ExpoExample = () => {
  const [devices, setDevices] = useState<Device[]>([]);
  const [loading, setLoading] = useState(false);
  const [connected, setConnected] = useState(false);
  const [connectedDevice, setConnectedDevice] = useState<Device | null>(null);
  const [mediaUrl, setMediaUrl] = useState('https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4');
  const [title, setTitle] = useState('大雄兔');
  const [playing, setPlaying] = useState(false);
  const [playbackStatus, setPlaybackStatus] = useState<PlaybackStatus | null>(null);
  const [volume, setVolume] = useState(50);
  const [runtimeInfo, setRuntimeInfo] = useState({ isExpo: false, platform: 'unknown' });

  // 初始化时设置运行环境信息
  useEffect(() => {
    try {
      // 通过Platform判断运行平台
      setRuntimeInfo({
        isExpo: Boolean(Platform.constants?.reactNativeVersion),
        platform: Platform.OS === 'ios' ? 'iOS' : Platform.OS === 'android' ? 'Android' : 'Unknown'
      });
    } catch (error) {
      console.error('获取环境信息失败:', error);
    }

    // 组件卸载时进行清理
    return () => {
      // 如果已连接，断开连接
      if (connected) {
        DlnaPlayer.disconnectDevice().catch((error: any) => {
          console.error('断开连接失败:', error);
        });
      }
    };
  }, [connected]);

  // 定期更新播放状态
  useEffect(() => {
    if (!connected) return;

    let intervalId: any = null;

    const updateStatus = async () => {
      try {
        const status = await DlnaPlayer.getPlaybackStatus();
        setPlaybackStatus(status);
        setPlaying(status.isPlaying);
      } catch (error) {
        console.error('获取播放状态失败:', error);
      }
    };

    // 每秒更新一次状态
    intervalId = setInterval(updateStatus, 1000);

    return () => {
      if (intervalId) clearInterval(intervalId);
    };
  }, [connected]);

  // 搜索设备
  const handleSearchDevices = async () => {
    try {
      setLoading(true);

      // 检查权限
      if (DlnaPlayer.checkPermission) {
        const permissionResult = await DlnaPlayer.checkPermission("network");
        if (permissionResult !== "granted" && DlnaPlayer.requestPermission) {
          const granted = await DlnaPlayer.requestPermission("network");
          if (!granted) {
            Alert.alert('权限请求', '未能获取所需权限，搜索设备功能可能无法正常使用。');
          }
        }
      }

      // 搜索设备
      const foundDevices = await DlnaPlayer.searchDevices();
      setDevices(foundDevices);

      if (foundDevices.length === 0) {
        Alert.alert('提示', '未找到设备，请确保设备在同一网络下并已开启。');
      }
    } catch (error: any) {
      console.error('搜索设备失败:', error);
      Alert.alert('错误', `搜索设备失败: ${error.message || '未知错误'}`);
    } finally {
      setLoading(false);
    }
  };

  // 连接设备
  const handleConnect = async (device: Device) => {
    try {
      setLoading(true);
      // 使用 id 属性连接设备
      const deviceId = device.id || device.deviceId;
      if (!deviceId) {
        throw new Error('设备ID不存在');
      }

      const result = await DlnaPlayer.connectDevice(deviceId);
      if (result) {
        setConnected(true);
        setConnectedDevice(device);
        Alert.alert('成功', `已连接至设备: ${device.name || deviceId}`);
      } else {
        Alert.alert('失败', '连接设备失败');
      }
    } catch (error: any) {
      console.error('连接设备失败:', error);
      Alert.alert('错误', `连接设备失败: ${error.message || '未知错误'}`);
    } finally {
      setLoading(false);
    }
  };

  // 断开连接
  const handleDisconnect = async () => {
    try {
      setLoading(true);
      const result = await DlnaPlayer.disconnectDevice();
      if (result) {
        setConnected(false);
        setConnectedDevice(null);
        setPlaying(false);
        setPlaybackStatus(null);
        Alert.alert('成功', '已断开设备连接');
      } else {
        Alert.alert('失败', '断开连接失败');
      }
    } catch (error: any) {
      console.error('断开连接失败:', error);
      Alert.alert('错误', `断开连接失败: ${error.message || '未知错误'}`);
    } finally {
      setLoading(false);
    }
  };

  // 播放媒体
  const handlePlay = async () => {
    if (!mediaUrl) {
      Alert.alert('提示', '请输入媒体地址');
      return;
    }

    try {
      setLoading(true);
      const result = await DlnaPlayer.play({
        url: mediaUrl,
        title: title
      });
      if (result) {
        setPlaying(true);
        Alert.alert('成功', '开始播放');
      } else {
        Alert.alert('失败', '播放失败');
      }
    } catch (error: any) {
      console.error('播放失败:', error);
      Alert.alert('错误', `播放失败: ${error.message || '未知错误'}`);
    } finally {
      setLoading(false);
    }
  };

  // 暂停/恢复
  const handlePauseResume = async () => {
    try {
      setLoading(true);
      if (playing) {
        const result = await DlnaPlayer.pause();
        if (result) {
          setPlaying(false);
        }
      } else {
        const result = await DlnaPlayer.resume();
        if (result) {
          setPlaying(true);
        }
      }
    } catch (error: any) {
      console.error('暂停/恢复失败:', error);
      Alert.alert('错误', `操作失败: ${error.message || '未知错误'}`);
    } finally {
      setLoading(false);
    }
  };

  // 停止播放
  const handleStop = async () => {
    try {
      setLoading(true);
      const result = await DlnaPlayer.stop();
      if (result) {
        setPlaying(false);
        setPlaybackStatus(null);
        Alert.alert('成功', '已停止播放');
      } else {
        Alert.alert('失败', '停止播放失败');
      }
    } catch (error: any) {
      console.error('停止播放失败:', error);
      Alert.alert('错误', `停止播放失败: ${error.message || '未知错误'}`);
    } finally {
      setLoading(false);
    }
  };

  // 设置音量
  const handleSetVolume = async (newVolume: number) => {
    try {
      const result = await DlnaPlayer.setVolume(newVolume);
      if (result) {
        setVolume(newVolume);
      }
    } catch (error) {
      console.error('设置音量失败:', error);
    }
  };

  // 跳转到指定位置
  const handleSeek = async (position: number) => {
    if (!playbackStatus) return;

    try {
      setLoading(true);
      const result = await DlnaPlayer.seekTo(position);
      if (!result) {
        Alert.alert('失败', '跳转失败');
      }
    } catch (error: any) {
      console.error('跳转失败:', error);
      Alert.alert('错误', `跳转失败: ${error.message || '未知错误'}`);
    } finally {
      setLoading(false);
    }
  };

  // 格式化时间
  const formatTime = (seconds: number): string => {
    const min = Math.floor(seconds / 60);
    const sec = Math.floor(seconds % 60);
    return `${min.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`;
  };

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar barStyle="dark-content" />
      <ScrollView contentContainerStyle={styles.scrollContent}>
        <Text style={styles.title}>DLNA Player Expo 示例</Text>

        {/* 环境信息 */}
        <View style={styles.infoCard}>
          <Text style={styles.infoTitle}>运行环境</Text>
          <Text>Expo环境: {runtimeInfo.isExpo ? '是' : '否'}</Text>
          <Text>平台: {runtimeInfo.platform}</Text>
        </View>

        {/* 设备搜索及列表 */}
        <View style={styles.section}>
          <TouchableOpacity
            style={styles.button}
            onPress={handleSearchDevices}
            disabled={loading}
          >
            <Text style={styles.buttonText}>
              {loading ? '搜索中...' : '搜索设备'}
            </Text>
            {loading && <ActivityIndicator color="#fff" style={styles.loader} />}
          </TouchableOpacity>

          <Text style={styles.sectionTitle}>
            发现的设备 ({devices.length})
          </Text>

          {devices.length === 0 ? (
            <Text style={styles.emptyText}>暂无设备，请点击搜索按钮</Text>
          ) : (
            devices.map((device) => (
              <TouchableOpacity
                key={device.id || device.deviceId || Math.random().toString()}
                style={[
                  styles.deviceItem,
                  connectedDevice?.id === device.id && styles.deviceItemActive,
                ]}
                onPress={() => handleConnect(device)}
                disabled={loading || connected}
              >
                <Text style={styles.deviceName}>{device.name || '未命名设备'}</Text>
                <Text style={styles.deviceId}>ID: {device.id || device.deviceId || '未知'}</Text>
                <Text style={styles.deviceModelName}>
                  型号: {device.model || device.modelName || '未知'}
                </Text>
              </TouchableOpacity>
            ))
          )}
        </View>

        {/* 已连接设备信息 */}
        {connected && connectedDevice && (
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>已连接设备</Text>
            <View style={styles.connectedDevice}>
              <Text style={styles.deviceName}>{connectedDevice.name}</Text>
              <Text style={styles.deviceId}>ID: {connectedDevice.id || connectedDevice.deviceId}</Text>
              <TouchableOpacity
                style={styles.disconnectButton}
                onPress={handleDisconnect}
                disabled={loading}
              >
                <Text style={styles.disconnectButtonText}>断开连接</Text>
              </TouchableOpacity>
            </View>
          </View>
        )}

        {/* 媒体控制 */}
        {connected && (
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>媒体控制</Text>

            <View style={styles.inputGroup}>
              <Text style={styles.inputLabel}>媒体地址:</Text>
              <TextInput
                style={styles.input}
                value={mediaUrl}
                onChangeText={setMediaUrl}
                placeholder="请输入媒体URL"
              />
            </View>

            <View style={styles.inputGroup}>
              <Text style={styles.inputLabel}>标题:</Text>
              <TextInput
                style={styles.input}
                value={title}
                onChangeText={setTitle}
                placeholder="请输入媒体标题"
              />
            </View>

            {/* 播放状态 */}
            {playbackStatus && (
              <View style={styles.playbackStatus}>
                <Text style={styles.statusText}>
                  状态: {playing ? '播放中' : '已暂停'}
                </Text>
                <Text style={styles.statusText}>
                  进度: {formatTime(playbackStatus.position)} / {formatTime(playbackStatus.duration)}
                </Text>
                <View style={styles.progressBar}>
                  <View
                    style={[
                      styles.progressFill,
                      {
                        width: `${(playbackStatus.position / playbackStatus.duration) * 100}%`
                      }
                    ]}
                  />
                </View>
                <View style={styles.seekButtons}>
                  <TouchableOpacity
                    style={styles.seekButton}
                    onPress={() => handleSeek(Math.max(0, playbackStatus.position - 10))}
                  >
                    <Text style={styles.seekButtonText}>-10秒</Text>
                  </TouchableOpacity>
                  <TouchableOpacity
                    style={styles.seekButton}
                    onPress={() => handleSeek(Math.min(playbackStatus.duration, playbackStatus.position + 10))}
                  >
                    <Text style={styles.seekButtonText}>+10秒</Text>
                  </TouchableOpacity>
                </View>
              </View>
            )}

            <View style={styles.controlButtonsRow}>
              <TouchableOpacity
                style={styles.controlButton}
                onPress={handlePlay}
                disabled={loading}
              >
                <Text style={styles.controlButtonText}>播放</Text>
              </TouchableOpacity>

              <TouchableOpacity
                style={[styles.controlButton, playing ? styles.pauseButton : styles.resumeButton]}
                onPress={handlePauseResume}
                disabled={loading}
              >
                <Text style={styles.controlButtonText}>
                  {playing ? '暂停' : '恢复'}
                </Text>
              </TouchableOpacity>

              <TouchableOpacity
                style={[styles.controlButton, styles.stopButton]}
                onPress={handleStop}
                disabled={loading}
              >
                <Text style={styles.controlButtonText}>停止</Text>
              </TouchableOpacity>
            </View>

            {/* 音量控制 */}
            <View style={styles.volumeControl}>
              <Text style={styles.volumeLabel}>音量: {volume}%</Text>
              <View style={styles.volumeButtons}>
                <TouchableOpacity
                  style={styles.volumeButton}
                  onPress={() => handleSetVolume(Math.max(0, volume - 10))}
                >
                  <Text style={styles.volumeButtonText}>-</Text>
                </TouchableOpacity>
                <View style={styles.volumeBar}>
                  <View
                    style={[
                      styles.volumeFill,
                      { width: `${volume}%` }
                    ]}
                  />
                </View>
                <TouchableOpacity
                  style={styles.volumeButton}
                  onPress={() => handleSetVolume(Math.min(100, volume + 10))}
                >
                  <Text style={styles.volumeButtonText}>+</Text>
                </TouchableOpacity>
              </View>
            </View>
          </View>
        )}
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
    paddingTop: Platform.OS === 'android' ? StatusBar.currentHeight : 0,
  },
  scrollContent: {
    padding: 16,
  },
  title: {
    fontSize: 22,
    fontWeight: 'bold',
    marginBottom: 16,
    textAlign: 'center',
  },
  infoCard: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 16,
    marginBottom: 16,
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
  },
  infoTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 8,
  },
  section: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 16,
    marginBottom: 16,
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 12,
  },
  button: {
    backgroundColor: '#2196F3',
    padding: 12,
    borderRadius: 6,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 16,
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '500',
  },
  loader: {
    marginLeft: 8,
  },
  emptyText: {
    textAlign: 'center',
    padding: 16,
    color: '#666',
  },
  deviceItem: {
    backgroundColor: '#f8f8f8',
    padding: 12,
    borderRadius: 6,
    marginBottom: 8,
  },
  deviceItemActive: {
    backgroundColor: '#e1f5fe',
    borderColor: '#2196F3',
    borderWidth: 1,
  },
  deviceName: {
    fontSize: 16,
    fontWeight: '600',
  },
  deviceId: {
    fontSize: 12,
    color: '#666',
    marginTop: 4,
  },
  deviceModelName: {
    fontSize: 12,
    color: '#666',
    marginTop: 2,
  },
  connectedDevice: {
    backgroundColor: '#e8f5e9',
    padding: 12,
    borderRadius: 6,
    borderColor: '#4CAF50',
    borderWidth: 1,
  },
  disconnectButton: {
    backgroundColor: '#f44336',
    padding: 8,
    borderRadius: 4,
    alignSelf: 'flex-start',
    marginTop: 8,
  },
  disconnectButtonText: {
    color: '#fff',
    fontWeight: '500',
  },
  inputGroup: {
    marginBottom: 12,
  },
  inputLabel: {
    fontSize: 14,
    fontWeight: '500',
    marginBottom: 4,
  },
  input: {
    backgroundColor: '#f0f0f0',
    borderRadius: 4,
    padding: 8,
    borderWidth: 1,
    borderColor: '#ddd',
  },
  playbackStatus: {
    marginVertical: 12,
    padding: 8,
    backgroundColor: '#f0f0f0',
    borderRadius: 6,
  },
  statusText: {
    fontSize: 14,
    marginBottom: 4,
  },
  progressBar: {
    height: 8,
    backgroundColor: '#ddd',
    borderRadius: 4,
    marginVertical: 8,
    overflow: 'hidden',
  },
  progressFill: {
    height: '100%',
    backgroundColor: '#4CAF50',
  },
  seekButtons: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 8,
  },
  seekButton: {
    backgroundColor: '#2196F3',
    padding: 6,
    borderRadius: 4,
    width: 70,
    alignItems: 'center',
  },
  seekButtonText: {
    color: '#fff',
    fontSize: 12,
  },
  controlButtonsRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 16,
  },
  controlButton: {
    flex: 1,
    backgroundColor: '#4CAF50',
    padding: 10,
    borderRadius: 4,
    alignItems: 'center',
    marginHorizontal: 4,
  },
  pauseButton: {
    backgroundColor: '#FFC107',
  },
  resumeButton: {
    backgroundColor: '#4CAF50',
  },
  stopButton: {
    backgroundColor: '#f44336',
  },
  controlButtonText: {
    color: '#fff',
    fontWeight: '500',
  },
  volumeControl: {
    marginTop: 16,
  },
  volumeLabel: {
    fontSize: 14,
    fontWeight: '500',
    marginBottom: 8,
  },
  volumeButtons: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  volumeButton: {
    backgroundColor: '#2196F3',
    width: 30,
    height: 30,
    borderRadius: 15,
    justifyContent: 'center',
    alignItems: 'center',
  },
  volumeButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  volumeBar: {
    flex: 1,
    height: 8,
    backgroundColor: '#ddd',
    borderRadius: 4,
    marginHorizontal: 10,
    overflow: 'hidden',
  },
  volumeFill: {
    height: '100%',
    backgroundColor: '#2196F3',
  },
});

export default ExpoExample;
